<?php  
namespace Wap;
use Think\Controller;
use Wap\Wechat;
use Wap\BrowserController;
/**
* 
*/
class AutoLoginController extends BrowserController
{
	private $weObj;
	function _initialize(){
		parent::_initialize();
		if(session("user")==null){
			if(session('isWx') == null){
				if(myCookie("USER_DATA")!=null){
					\Think\Log::write("auto:".myCookie("USER_DATA"));
					$url = C('SERVER_URL')."/loginByCookie";
					$msg = httpPost($url);
					if($msg->code == '200'){
						session('user',$msg->info);
					}else if(isset($msg->code)){
						cookie('USER_DATA',null,0);
					}
				}
			}else{
				\Think\Log::write('微信浏览器' );
				if(session('openid')){
					$user = array(
						'userId'=> session('openid'),
					);
					$msg = httpPost(C('SERVER_URL').'/loginByUserId',$user);
					if($msg->code == 200){
						session('user',$msg->info);
						return ;
					}else{
				        echo "登录失败！";
				        exit();
			        }
				} else{									
		    	$selfUrl = getSelfUrl();
					\Think\Log::write('selfUrl => ' . $selfUrl);
		      $this->weObj = new Wechat;
		      $state = time();
		      $codeUrl = $this->weObj->getOauthRedirect($selfUrl, $state, 'snsapi_userinfo');
		      \Think\Log::write('codeUrl => ' . $codeUrl);
		      if(empty($_GET['code']) && empty($_GET['state'])) {
		        \Think\Log::write('跳转到 codeurl');
			      header("Location:$codeUrl");
			      exit();
		      } 
		      \Think\Log::write('有Code');
		      $authResult = $this->weObj->getOauthAccessToken();
		      \Think\Log::write('authResult => ' . dump($authResult, false));
		      $openid = null;
		      if($authResult) {
			      $this->openid = $authResult['openid'];
			      $wxuserinfo = $this->weObj->getOauthUserinfo($authResult['access_token'], $this->openid);
			      \Think\Log::write('网页获取用户信息 =》 '. dump($wxuserinfo, false));
			      if($wxuserinfo) {
				      $user = array(
											'userId'	=> $wxuserinfo['openid'],
									  'nickname'	=> $wxuserinfo['nickname'],
									      'head'	=> $wxuserinfo['headimgurl'],
							);
			      }
			      session('openid', $this->openid);
			      \Think\Log::write("json_encode:".json_encode($user));
			    
			      $msg = httpPost(C('SERVER_URL').'/loginByUserId',$user);
			      if($msg->code == 200){
				      session('user',$msg->info);
				      return;
				  }else{
					  $msg = httpPost(C('SERVER_URL').'/registerByUserId',$user);
				      if($msg->code == 200){
					      session('user',$msg->info);
					      return;
				      }else{
				         header("Content-type: text/html; charset=utf-8"); 
					     echo "登录失败！";
					     exit();
				      }      
				  }  
		     } else {
		       header("Content-type: text/html; charset=utf-8"); 
			     echo "用户信息获取失败！";
			     exit();
		     }
			       
		    }
			}
		}
	}
}

?>